<template>
  <div class="main">
    <MyHeader :searchForm="searchForm" @search="handleSearch"></MyHeader>

    <el-card class="bottom">
      <div class="table-overview">
        <div class="left">
          <span>社团成员列表</span>
          <span class="total"
            >共
            <span>{{ pagination.total }}</span>
            条记录
          </span>

          <el-button
            class="delete-btn"
            type="danger"
            @click="handleDeleteList"
            v-show="computedSelectedTable.length >= 2"
            >删除{{ computedSelectedTable.length }}条</el-button
          >
        </div>
        <div class="right">
          <el-button type="primary" @click="showImportDialog"
            >批量导入</el-button
          >
          <el-button type="primary" @click="exportSelected">导出选中</el-button>
          <el-button type="primary" @click="showExportAllDialog"
            >导出全部</el-button
          >
          <el-button type="primary" @click="showAddDialog">新增</el-button>
        </div>
      </div>
      <Table
        ref="tableComponent"
        :tableData="tableData"
        :selectedTable="selectedTable"
        :pagination="pagination"
        @edit="showEditDialog"
        @delete="showDeleteDialog"
        @selectionChange="handleSelectionChange"
        @updateCell="handleUpdateCell"
      >
      </Table>
      <Pagination
        :pagination="pagination"
        @currentChange="handleCurrentChange"
      ></Pagination>

      <AddDialog
        :addDialogVisible="addDialogVisible"
        @closeAddDialog="handleCloseAddDialog"
        @confirm="handleConfirmAdd"
      ></AddDialog>

      <EditDialog
        :editForm="editForm"
        :editDialogVisible="editDialogVisible"
        @closeEditDialog="handleCloseEditDialog"
        @confirm="handleConfirmEdit"
      >
      </EditDialog>

      <DeleteDialog
        :deleteDialogVisible="deleteDialogVisible"
        @closeDeleteDialog="handleCloseDeleteDialog"
        @confirm="handleConfirmDelete"
      >
        确认删除这行数据吗？
      </DeleteDialog>

      <ExportDialog
        :tableData="exportTableData"
        :exportAllDialogVisible="exportAllDialogVisible"
        @closeExportAllDialog="handleCloseExportAllDialog"
      ></ExportDialog>

      <ImportDialog
        :importDialogVisible="importDialogVisible"
        @closeImportDialog="handleCloseImportDialog"
        @upload="handleUpload"
      >
      </ImportDialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import Table from "./components/Table.vue";
import Pagination from "@/components/Pagination.vue";
import DeleteDialog from "@/components/DeleteDialog.vue";
import AddDialog from "./components/AddDialog.vue";
import EditDialog from "./components/EditDialog.vue";
import ExportDialog from "./components/ExportDialog.vue";
import ImportDialog from "./components/importDialog.vue";
import MyHeader from "./components/MyHeader.vue";

import { reactive, toRefs, onMounted, ref, computed } from "vue";
import { ElMessage } from "element-plus";

import {
  getList,
  editMember,
  deleteMemberPositions,
  deleteMember,
  deleteMemberList,
} from "@/api/member/index.ts";
import lodash from "lodash";
import { getAll } from "@/api/member";
import { useStore } from "vuex";

import { formatDate } from '@/utils/formatDate';

const tableData = reactive([]);

const state = reactive({
  addDialogVisible: false,
  deleteDialogVisible: false,
  editDialogVisible: false,
  exportAllDialogVisible: false,
  editForm: {},
});

const {
  addDialogVisible,
  deleteDialogVisible,
  editDialogVisible,
  exportAllDialogVisible,
  editForm,
} = toRefs(state);

// 批量导入
const importDialogVisible = ref(false);
const showImportDialog = () => {
  importDialogVisible.value = true;
};
const handleCloseImportDialog = () => {
  importDialogVisible.value = false;
};

const handleUpload = () => {
  handleCloseImportDialog();

  initTableData();

  ElMessage({
    message: '导入成功',
    type: 'success'
  })
}

// 获取数据
const pagination = reactive({
  // 当前页
  currentPage: 1,

  // 一页数据条数
  pageSize: 10,

  // 总数据条数
  total: 0,
});

const handleCurrentChange = (page: number) => {
  initTableData();
};

async function getDataList(
  page: number,
  limit: number,
  condition?: {
    memberName?: string,
    sex?: string,
    organization?: number
  }
) {
  const { data: res } = await getList(page, limit, {
    ...condition,
  });
  if (res.code === 200) {
    pagination.total = res.data.total;
    // 清空数组
    tableData.splice(0, tableData.length);

    for (const item of res.data.records) {
      const obj = {
        rowId: item._id,
        memberName: item.name,
        sex: item.sex,
        studentID: item.studentID,
        college: item.college,
        joinTime: formatDate(new Date(item.joinTime)),
        phone: item.phone,
        positions: [],
      };

      for (let i = 0, len = item.organizations.length; i < len; i++) {
        obj.positions.push({
          organization: item.organizations[i],
          position: item.positions[i]
        } as never)
      }

      // for (const p of item.positions) {
      //   obj.positions.push({
      //     id: p.id,
      //     organization: p.organizationId + "",
      //     position: p.positionId + "",
      //   } as never);
      // }

      tableData.push(obj as never);
    }

    console.log(tableData);
  }
}

const searchForm: IObj = reactive({
  memberName: "",
  college: "",
  organization: ""
});

const handleSearch = () => {
  const obj: IObj = {};

  const map: IObj = {
    memberName: "name",
    college: "college",
    organization: "organization",
  };

  for (const item in searchForm) {
    if (searchForm[item] != "") {
      obj[map[item]] = searchForm[item];
    }
  }

  getDataList(pagination.currentPage, pagination.pageSize, obj);
};

function initTableData() {
  // getDataList(pagination.currentPage, pagination.pageSize);
  handleSearch();
}

initTableData();

// 事件

const showAddDialog = () => {
  addDialogVisible.value = true;
};

const handleCloseAddDialog = () => {
  addDialogVisible.value = false;
};
const handleConfirmAdd = () => {
  ElMessage({
    message: "新增成功",
    type: "success",
  });

  initTableData();
};

const showEditDialog = (row: any) => {
  editDialogVisible.value = true;
  editForm.value = lodash.cloneDeep(row);

  if ((editForm.value as IObj).positions.length === 0) {
    (editForm.value as IObj).positions.push({
      organization: "",
      position: "",
    });
  }

  console.log(editForm.value);
};

const handleCloseEditDialog = () => {
  editDialogVisible.value = false;
};

const store = useStore();

const handleConfirmEdit = async (form: IObj = editForm.value as IObj) => {
  const memberInfo: IObj = {
    _id: form.rowId,
    name: form.memberName,
    sex: form.sex,
    studentID: form.studentID,
    college: form.college,
    joinTime: form.joinTime,
    phone: form.phone,
    positions: form.positions
  };

  handleCloseEditDialog();

  const { data: res } = await editMember(memberInfo);

  if (res.code === 200) {
    ElMessage({
      message: "修改成功",
      type: "success",
    });
  }

  initTableData();

  // console.log(editForm.value);
};

const handleUpdateCell = async (index: number, attribute: string) => {
  handleConfirmEdit(tableData[index]);
};

let deleteId: number;
const showDeleteDialog = (row: any) => {
  deleteDialogVisible.value = true;
  deleteId = row.rowId;
};

const handleCloseDeleteDialog = () => {
  deleteDialogVisible.value = false;
};

const handleConfirmDelete = async () => {
  const { data: res } = await deleteMember(deleteId);

  if (res.code === 200) {
    handleCloseDeleteDialog();

    if (selectedTable[pagination.currentPage] !== undefined) {
      selectedTable[pagination.currentPage] = selectedTable[
        pagination.currentPage
      ].filter((item: IObj) => item.rowId != deleteId);
    }

    initTableData();

    ElMessage({
      message: "删除成功",
      type: "success",
    });
  }
};

const handleDeleteList = async () => {
  const idList = [];

  for (const item of computedSelectedTable.value) {
    idList.push(item.rowId);
  }

  console.warn(idList);
  console.warn(selectedTable);

  const { data } = await deleteMemberList(idList);

  if (data.code === 200) {
    ElMessage({
      message: "删除成功",
      type: "success",
    });

    for (const deleteId of idList) {
      const page = Math.ceil(pagination.total / pagination.pageSize);

      for (let i = 1; i <= page; i++)
      if (selectedTable[i] !== undefined) {
        selectedTable[i] = selectedTable[i].filter((item: IObj) => item.rowId != deleteId);
      }
    }

    initTableData();
  }
};

const exportTableData: IObj[] = reactive([]);

const showExportAllDialog = async () => {
  const { data: res } = await getAll();
  if (res.code === 200) {
    // 清空数组
    exportTableData.splice(0, exportTableData.length);

    for (const item of res.data) {
      const obj = {
        rowId: item._id,
        memberName: item.name,
        sex: item.sex,
        studentID: item.studentID,
        college: item.college,
        joinTime: formatDate(new Date(item.joinTime)),
        phone: item.phone,
        positions: [],
      };

      for (let i = 0, len = item.organizations.length; i < len; i++) {
        obj.positions.push({
          organization: item.organizations[i],
          position: item.positions[i]
        } as never)
      }

      exportTableData.push(obj as never);
    }

  }
  
  exportAllDialogVisible.value = true;
};

const handleCloseExportAllDialog = () => {
  exportAllDialogVisible.value = false;
};

let selectedTable: IObj = reactive({});

const computedSelectedTable = computed(() => {
  const result = [];

  for (const item in selectedTable) {
    if (selectedTable[item].length != 0) {
      result.push(...selectedTable[item]);
    }
  }
  return result;
});

const handleSelectionChange = (selection: IOrganizationTable[]) => {
  selectedTable[pagination.currentPage] = lodash.cloneDeep(selection);
};
const exportSelected = () => {
  if (computedSelectedTable.value.length <= 0) {
    return;
  }

  exportTableData.splice(0, exportTableData.length);

  for (const row of computedSelectedTable.value) {

    exportTableData.push(row);
  }

  exportAllDialogVisible.value = true;
};
</script>

<style lang="less" scoped>
.bottom {
  margin-top: 28px;

  .table-overview {
    display: flex;
    justify-content: space-between;
    height: 60px;
    line-height: 30px;

    .left {
      .total {
        margin-left: 50px;
      }

      .delete-btn {
        margin-left: 20px;
      }
    }
  }
}
</style>
